package com.funny.filter;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author Ming
 * @description Gateway - 局部 自定义过滤器
 * @fileSimpleName CheckAuthGatewayFilterFactory
 * @fileName com.funny.filter.CheckAuthGatewayFilterFactory
 * @date 2024年06月28日 16:52
 */
@Slf4j
@Component
public class CheckAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckAuthGatewayFilterFactory.Config> {

    public CheckAuthGatewayFilterFactory() {
        super(CheckAuthGatewayFilterFactory.Config.class);
    }

    // - CheckAuth=MING
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("value");
    }

    @Override
    public GatewayFilter apply(CheckAuthGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            String name = exchange.getRequest().getQueryParams().getFirst("name");
            System.out.println("CheckAuthGatewayFilterFactory name={" + name + "}");
            System.out.println("CheckAuthGatewayFilterFactory config.value name={}" + config.value + "}");
            if (StringUtils.isNoneBlank(name)) {
                if (config.value.equals(name)) {
                    return chain.filter(exchange);
                } else {
                    exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                    return exchange.getResponse().setComplete();
                }
            }
            return chain.filter(exchange);
        };
    }


    public static class Config {

        private String value;

        public void setValue(String value) {
            this.value = value;
        }
    }

}
